package com.javabasic.concurrency;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class TestForkJoinPool {

    public static void main(String[] args) {

        ForkJoinPool pool = new ForkJoinPool();

        ForkJoinTask<Long> task = new ForkJoinSumCalculate(0L,1000000L);

        Long result = pool.invoke(task);

        System.out.println(result);

    }
}

class ForkJoinSumCalculate extends RecursiveTask<Long> {

    private static  final long serialVersionUID = -2L;

    private long start;
    private long end;

    private static final long THURSHOLD = 10000L; // 临界值

    public ForkJoinSumCalculate(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long len = end - start;

        if (len <= THURSHOLD) {
            long sum = 0;

            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {
            long middle = (end + start) / 2;

            ForkJoinSumCalculate left = new ForkJoinSumCalculate(start,middle);
            left.join(); // 进行拆分，同时压入线程队列

            ForkJoinSumCalculate right = new ForkJoinSumCalculate(middle+1,end);
            right.join();

            return left.join() + right.join();
        }
    }
}
